<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "user_friend".
 *
 * @property int $id ID
 * @property int $userid 用户id
 * @property int $friendid 好友id
 * @property char letter 名称首字母
 * @property char remarks 好友备注
 * @property int $addtime 添加时间
 */
class UserFriend extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user_friend';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['userid', 'friendid', 'addtime'], 'required'],
            [['userid', 'friendid', 'addtime'], 'integer'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'userid' => '用户id',
            'friendid' => '好友id',
            'addtime' => '添加时间',
        ];
    }
    
    
    public static function getFriendsList($userid){
        $sql = "select * from user_friend where userid=$userid order by letter asc";
        $command = \Yii::$app->db->createCommand($sql);
        $data = $command->queryAll();
        foreach($data as $key=>$value){
            $data[$key]['headimg'] = User::getUserHeadImg($value['friendid']);
        }
        return $data;
    }
    
    public static function CheckIsFriend($user1,$user2){
        $sql = "select count(id) from user_friend where userid=$user1 and friendid=$user2";
        $command = \Yii::$app->db->createCommand($sql);
        $data = $command->queryOne();
        if(!empty($data)){
            return true;
        }else{
            return false;
        }
    }
    /***
     * 更新好友关系中的会话ID
     */
    public static function UpdateChatid($user1,$user2,$chatid){
        $sql = "update user_friend set chatid=$chatid where userid=$user1 and friendid=$user2 ";
        $command = \Yii::$app->db->createCommand($sql);
        $command->execute();
        
        $sql = "update user_friend set chatid=$chatid where userid=$user2 and friendid=$user1 ";
        $command = \Yii::$app->db->createCommand($sql);
        $command->execute();
    }
}
